#!/usr/bin/env python3
"""
工具函数模块
"""
import asyncio
import json
import random
from datetime import datetime, timezone
from pathlib import Path

# ---------------------- 工具函数：JSONL追加（异步安全） ----------------
async def append_jsonl(entry: dict, path: str):
    """
    将条目以JSONL格式异步追加到文件中

    Args:
        entry (dict): 要写入的条目字典
        path (str): 日志文件路径
    """
    loop = asyncio.get_running_loop()
    s = json.dumps(entry, ensure_ascii=False)
    def _write():
        p = Path(path)
        p.parent.mkdir(parents=True, exist_ok=True)
        with p.open("a", encoding="utf-8") as f:
            f.write(s + "\n")
    await loop.run_in_executor(None, _write)

def now_iso():
    """
    获取当前UTC时间的ISO格式字符串

    Returns:
        str: ISO格式的时间字符串
    """
    return datetime.now(timezone.utc).isoformat()

# ---------------------- 工具函数 --------------------------
# 模拟命令执行时间
async def simulate_command_execution(min_time=0.1, max_time=1.5):
    # 模拟命令执行的延迟
    await asyncio.sleep(random.uniform(min_time, max_time))

# 检测是否为自动化扫描工具
def is_automated_scan(data_bytes):
    # 检测常见的nmap探测模式
    data_str = data_bytes.decode('utf-8', errors='ignore')

    # Nmap探测特征
    nmap_patterns = [
        'Nmap', 'script', 'vuln', 'banner', 'ssh', 'telnet',
        '<?xml', 'GET /', 'HEAD /', 'OPTIONS *', 'PUT /', 'POST /'
    ]

    return any(pattern in data_str for pattern in nmap_patterns)
